<?php
/**
 * wechat php test
 */
namespace App\Http\Controllers\Api\V1\Manager\Wx;


use App\Libs\httpUtil;
use App\Models\User;
use App\Models\WxAutoResponse;
use App\Services\Wx\AliService;

class WxApi
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

        //valid signature , option
        if ($this->checkSignature()) {
            echo $echoStr;
            exit;
        }
    }

    public function responseMsg()
    {

        $postArr = file_get_contents("php://input");
        $a = WxAutoResponse::where("subscribe", 1)->first();
        $postObj = simplexml_load_string($postArr);
        if (strtolower($postObj->MsgType) == 'event') {
            //如果是关注事件(subscribe)

            if (strtolower($postObj->Event == 'subscribe')) {
                //回复用户消息
                $toUser = $postObj->FromUserName;
                $fromUser = $postObj->ToUserName;
                $this->getUserInfoByWx($toUser);
                $time = time();
                $msgType = 'text';
                $content = $a['content'];
                $template = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";
                $info = sprintf($template, $toUser, $fromUser, $time, $msgType, $content);
                echo $info;
            }
        }

//回复纯文本或单图文消息
        if (($postObj->MsgType) == 'text') {

            $toUser = $postObj->FromUserName;
            $fromUser = $postObj->ToUserName;
            $arr = WxAutoResponse::where('keyWords', $postObj->Content)->get()->toArray();

            $template = "<xml>
						<ToUserName><![CDATA[%s]]></ToUserName>
						<FromUserName><![CDATA[%s]]></FromUserName>
						<CreateTime>%s</CreateTime>
						<MsgType><![CDATA[%s]]></MsgType>
						<ArticleCount>" . count($arr) . "</ArticleCount>
						<Articles>";

            foreach ($arr as $k => $v) {
                if ($v['responseType'] == 3) {
                    $template .= "<item>
							<Title><![CDATA[" . $v['title'] . "]]></Title> 
							<Description><![CDATA[" . $v['content'] . "]]></Description>
							<PicUrl><![CDATA[" . $v['coverImage'] . "]]></PicUrl>
							<Url><![CDATA[" . $v['url'] . "]]></Url>
							</item>";
                    $msgType = "news";
                    $time = time();
                    $template .= "</Articles>
						</xml> ";

                    echo sprintf($template, $toUser, $fromUser, $time, $msgType);
                }

                if ($v['responseType'] == 1) {
                    $time = time();
                    $msgType = 'text';
                    $content = $v['content'];
                    $template1 = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";
                    $info = sprintf($template1, $toUser, $fromUser, $time, $msgType, $content);
                    echo $info;
                }
                if ($v['responseType'] == 2) {

                    $time = time();
                    $msgType = 'image';
                    $template1 = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Image><MediaId><![CDATA[media_id]]></MediaId></Image>
							</xml>";
                    $info = sprintf($template1, $toUser, $fromUser, $time, $msgType);
                    echo $info;
                }


            }

            $time = time();
            $msgType = 'text';
            $content = $a['content'];
            $template1 = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							</xml>";
            $info = sprintf($template1, $toUser, $fromUser, $time, $msgType, $content);
            echo $info;

        }

    }


    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }

        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);

        if ($tmpStr == $signature) {
            return true;
        } else {
            return false;
        }
    }

    public function getUserInfoByWx($openId)
    {
        $wx = new wxCommentController();
        $access_token = $wx->getAccessToken();
        $url = "https://api.weixin.qq.com/cgi-bin/user/info?openid=" . $openId . '&access_token=' . $access_token . "&lang=zh_CN";
        $http = new httpUtil();
        $result = $http->http_get($url);
        $result = json_decode($result, true);
        $unionid = $result['unionid'];
        $wxOpenId = $result['openid'];
        $status = User::where('unionId', $unionid)->first();
        if ($status) {
            User::where('unionId', $unionid)->update(['wxOpenId' => $wxOpenId]);
        } else {
            $res['nickName'] = $result['nickname'];
            $res['avatarUrl'] = $result['headimgurl'];
            $res['wxOpenId'] = $wxOpenId;
            $res['unionId'] = $unionid;
            $res['createTime'] = date('Y-m-d H:i:s', time());
            User::create($res);
        }
        return;

    }
}

?>